package cn.openea.perpartner.meily.scheduledtasks.provider;

import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.Provider;
import cn.openea.perpartner.meily.web.service.IGroupBuyingSubService;
import cn.openea.perpartner.meily.web.service.IProviderService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ysk
 * @version 1.0.1
 * @Description 区域服务商出单状态更改任务
 * @createTime 2023年07月17日 18:48:00
 */
@Slf4j
@Component
public class ProviderIssueChangeTask {

    @Resource
    private IProviderService providerService;
    @Resource
    private IGroupBuyingSubService groupBuyingSubService;


    /**
     * 获取上一天0点到现在的购买记录数据 过滤掉购买者和发起人为同一人的数据
     * 每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void issueStatusChange() {
        log.info("provide issue status change task start execution");
        LocalDate currentDate = LocalDate.now();
        // 获取到区域开单的区域服务商的编号
        List<String> providerIds = groupBuyingSubService.selectListByDateRange(currentDate.minusDays(1), currentDate)
                .stream()
                .filter(item -> !item.getPartnerId().equals(item.getInitiatorId()))
                .map(GroupBuyingSub::getInitiatorId)
                .distinct()
                .collect(Collectors.toList());
        if (providerIds.isEmpty()) {
            return;
        }
        providerService.update(new LambdaUpdateWrapper<Provider>()
                .in(Provider::getUserId, providerIds)
                .set(Provider::getIssue, 1));
    }

}
